<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/6 0006
 * Time: 17:04
 */
namespace app\modules\content\controllers;

use app\libs\Pager;
use yii;
use app\libs\ApiControl;
use app\modules\content\models\Classes;
use app\modules\content\models\ClassesSdk;
use app\libs\GetData;

class ClassesController extends ApiControl
{
    public $enableCsrfValidation = false;

    // 所有课程的显示
    public function actionIndex()
    {
        // 从数据库获取数据
        $page = Yii::$app->request->get('page',1);
        $cate = Yii::$app->request->get('cate');
        $subject = Yii::$app->request->get('subject');
        $score = Yii::$app->request->get('score');
        $beginTime = strtotime(Yii::$app->request->get('beginTime'));
        $endTime = strtotime(Yii::$app->request->get('endTime'));
        $classesPort = Yii::$app->request->get('classesPort');
        $where = ' where 1=1';
        if ($subject != false) {
            $where .= " and subject= $subject";
        }
        if ($score != false) {
            $where .= " and score= $score";
        }
        if ($cate != false) {
            $where .= " and cate=$cate";
        }
        if ($beginTime != false) {
            $where .= " and createTime>=$beginTime";
        }
        if ($endTime != false) {
            $where .= " and createTime<=$endTime";
        }
        if ($classesPort != false) {
            $where .= " and classesPort= $classesPort";
        }
        $offset = 15 * ($page - 1);
        $count = Yii::$app->db->createCommand("select count(*) as count from {{%classes}} $where")->queryOne();
        $data = Yii::$app->db->createCommand("select * from {{%classes}} $where order by id desc limit $offset,15")->queryAll();
        $url = "/content/classes/index?cate=$cate&score=$score&classesPort=$classesPort&subject=$subject&beginTime=$beginTime&endTime=$endTime&page";
        $count = $count['count'];
        $page = new Pager("$url", $count, $page, 15);
        $str = $page->GetPager();
        return $this->render('index', ['data' => $data,'str'=>$str]);
    }

    // 添加课程
    public function actionAdd()
    {
        if (!$_POST) {
            // 判断是修改还是添加$id
            $id = Yii::$app->request->get('id', '');
            $classesTag = json_encode(Classes::courseCategory());
            if (empty($id)) {
                return $this->render('add',['classesTag'=>$classesTag,'classesSdk'=>[]]);
            } else {
                $data = Yii::$app->db->createCommand("select * from {{%classes}} where id=" . $id)->queryOne();
                // 查询课程sdk
                $classesSdk = ClassesSdk::getSdk($id);
                return $this->render('add', ['data' => $data,'classesTag'=>$classesTag,'classesSdk'=>$classesSdk]);
            }
        } else {
            $getdata = new GetData();
            $must = array('name' => '课程名称', 'cate' => '分类', 'price'=>'价格');
            $data = $getdata->PostData($must, 'classes');
            $classesSdk = Yii::$app->request->post('classesSdk',[]);
            foreach ($classesSdk as $k=>$v){
                if(!trim($v['sdk'])){
                    unset($classesSdk[$k]);
                }
            }
            $classesSdk = array_values($classesSdk);
            if (empty($data['id'])) {
                $re = Yii::$app->db->createCommand()->insert("{{%classes}}", $data)->execute();
                $lastId = Yii::$app->db->getLastInsertId();
                // 处理视频集
                foreach ($classesSdk as $key => $value) {
                    $model = new ClassesSdk();
                    $model->classesId = $lastId;
                    $model->sdk = $value['sdk'];
                    $model->pic = $value['pic'];
                    $model->type = $value['type'];
                    $model->integral = $value['integral'];
                    $model->sort = $key+1;
                    $model->save();
                }
            } else {
                $model = new Classes();
                $re = $model->updateAll($data, 'id=:id', array(':id' => $data['id']));
                // 处理视频集
                $remain = $classesSdk;
                $sdkArr = ClassesSdk::find()->where("classesId={$data['id']}")->all();
                foreach ($sdkArr as $k=>$v){
                    if(isset($classesSdk[$k])){
                        foreach ($classesSdk[$k] as $k2=>$v2){
                            $v->$k2 = $v2;
                        }
                        $v->save();
                        array_shift($remain);
                    }else{
                        ClassesSdk::deleteAll("id={$v->id}");
                    }
                }
                //有多余的内容
                foreach ($remain as $k=>$v){
                    $v['classesId'] = $data['id'];
                    Yii::$app->db->createCommand()->insert(ClassesSdk::tableName(),$v)->execute();
                }

            }
            if ($re) {
                $this->redirect('index');
            } else {
                echo '<script>alert("数据添加\修改失败，请重试");history.go(-1);</script>';
                die;
            }
        }
    }

    //删除课程
    public function actionDel()
    {
        $id = Yii::$app->request->get('id', '');
        $model = new Classes();
        $re = Classes::deleteAll("id=:id", array(':id' => $id));
        if ($re) {
            ClassesSdk::deleteAll("classesId=:id", array(':id' => $id));
            echo true;
        }
    }

}